package com.shop.controller;

import com.shop.pojo.Employee;
import com.shop.pojo.Leavebill;
import com.shop.service.LeaveBillService;
import com.shop.service.WorkFlowService;
import com.shop.utils.Constants;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
public class WorkFlowController {

    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private LeaveBillService leaveBillService;
    @Autowired
    private TaskService taskService;


    // 1.发布流程（创建部署）
    @RequestMapping(value = "/deployProcess")
    public String deployProcess(MultipartFile multipartFile, String processName) throws IOException {

        this.workFlowService.saveProcess(processName, multipartFile.getInputStream());

        System.out.println("\n Process发布成功！\n act_re_deployment.NAME_ : "+ processName + " 部署成功! \n");
            // act_re_deployment.NAME_

        return "add_process";

    }


    // 2.【提交请假信息（开始流程）】 -- 步骤: 1.保存【请假信息】 2.【启动流程】
    @RequestMapping(value = "/saveStartLeave")
    public String saveStartLeave(Leavebill leaveBill, HttpSession session) {

        Employee employee = (Employee) session.getAttribute(Constants.GLOBLE_USER_SESSION);

    // 1.封装【LeaveBill】 <- 因为 获取的leaveBill 不完整, 需要手动给她补充参数
        leaveBill.setLeavedate(new Date());
        leaveBill.setState(1);
        leaveBill.setUserId(employee.getId());

    // 2.保存【请假信息】 <-- 【状态】用来区分【当前流程】是否【正在运行】
        // 2-1. 保存【请假事件】
        this.leaveBillService.saveLeaveBill(leaveBill);

            // 一旦插入成功, 如何立马 return 数据库中的 leavebill.id值

        // 2-2. 启动【工作流】的流程（往前推进）
        this.workFlowService.startProcess(leaveBill.getId(), employee.getName());
            // UserID -> leaveId
        //        this.workFlowService.startProcess(employee.getName());

        return "redirect:/taskList";
    }


    /*
    3.【请假管理 - 我的待办事务】显示的 taskList -> 通过【用户名】查找
    ---------------------------------------------
    processEngine.createTaskService()
        .createTaskQuery()
        .taskAssignee(name)  <-- employee.getName()

    */
    @RequestMapping(value = "/taskList")
    public ModelAndView tasklist(HttpSession session) {

        ModelAndView mv = new ModelAndView();

        // 从 session 中取出 用户名(Assginee)
        Employee employee = (Employee) session.getAttribute(Constants.GLOBLE_USER_SESSION);

        // 查询操作
        List<Task> list = this.workFlowService.findTaskListByName(employee.getName());

        // 1.将查询出来的 taskList任务, 存储在域中
        mv.addObject("taskList", list);
        // 跳转jsp
        mv.setViewName("workflow_task");
        return mv;
    }


    /* 4.查询【请假单信息】
    -------
    【请假管理 - 我的待办事务 - 办理业务】 下方显示的 TaskForm
    ------------
    taskId => 前端URI?userId=Xxx 传入
    */
    @RequestMapping("viewTaskForm")
    public ModelAndView viewTaskForm(String taskId) {

        ModelAndView mv = new ModelAndView();

        // 1. 上方：用 taskId 查出 leavebill.ID_ 对应的数据
        Leavebill leaveBillByTaskId = this.leaveBillService.findLeaveBillByTaskId(taskId);

        // 2. 下方：查询【批假信息】 核心：TASK_ID_ & MESSAGE_
        List<Comment> commentListByTaskId = this.workFlowService.findCommentListByTaskId(taskId);

        mv.addObject("taskId", taskId); // 必须写,【办理任务】通过GET方式【?taskId=Xxx】传入, 若后续要使用,必须传入ModelAndView域中
        mv.addObject("bill", leaveBillByTaskId);
        mv.addObject("commentList", commentListByTaskId);
        mv.setViewName("approve_leave"); // 跳转到jsp视图 -> approve_leave.jsp
        return mv;
    }


    /* 5.【主管审批】
        - 保存主管【批注信息】 & 【完成任务】
    * */
    @RequestMapping("submitTask") // id 从 viewTaskForm的ModelAndView.setObject()传入/approve_leave.jsp的<input ${bill.id}传入
    public String submitTask(long id, String taskId, String comment, HttpSession session) {

        // 获取【员工类】
        Employee employee = (Employee) session.getAttribute(Constants.GLOBLE_USER_SESSION);

        // 保存【批注信息】
        this.workFlowService.submitTask(id, taskId, comment, employee.getName());

//        this.workFlowService.submitTask(id, taskId, comment, employee.getName());

        // 完成任务
        this.taskService.complete(taskId);

        return "redirect:/taskList";
    }


}
